# -*- coding: utf-8 -*-

"""
    http://projecteuler.net/problem=18
    
    PROBLEM

    By starting at the top of the triangle below and moving to adjacent numbers
    on the row below, the maximum total from top to bottom is 23.

    3
    7 4
    2 4 6
    8 5 9 3

    That is, 3 + 7 + 4 + 9 = 23.

    Find the maximum total from top to bottom of the triangle below:
    
    75
    95 64
    17 47 82
    18 35 87 10
    20 04 82 47 65
    19 01 23 75 03 34
    88 02 77 73 07 63 67
    99 65 04 28 06 16 70 92
    41 41 26 56 83 40 80 70 33
    41 48 72 33 47 32 37 16 94 29
    53 71 44 65 25 43 91 52 97 51 14
    70 11 33 28 77 73 17 78 39 68 17 57
    91 71 52 38 17 14 91 43 58 50 27 29 48
    63 66 04 68 89 53 67 30 73 16 69 87 40 31
    04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

    NOTE: As there are only 16384 routes, it is possible to solve this problem
    by trying every route. However, Problem 67, is the same challenge with a
    triangle containing one-hundred rows; it cannot be solved by brute force,
    and requires a clever method! ;o)
    
    
    NOTES
    A couple false starts. But once I recognized the solution, it was all so
    obvious. Left the path-walking stuff in, even though it is not needed
    for the solution.
    
    
    REFERENCES
    
    
    PERFORMANCE
    time <function solution at 0x7f50b257d7d0>: 0.000564 s
"""
#
# Import
#
import time


#
# Globals / Constants
#
TRIANGLE = """
    75
    95 64
    17 47 82
    18 35 87 10
    20 04 82 47 65
    19 01 23 75 03 34
    88 02 77 73 07 63 67
    99 65 04 28 06 16 70 92
    41 41 26 56 83 40 80 70 33
    41 48 72 33 47 32 37 16 94 29
    53 71 44 65 25 43 91 52 97 51 14
    70 11 33 28 77 73 17 78 39 68 17 57
    91 71 52 38 17 14 91 43 58 50 27 29 48
    63 66 04 68 89 53 67 30 73 16 69 87 40 31
    04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""

def timeit(f):
    def timer():
        t0 = time.time()
        returned = f()
        print "time %s: %.6f s" % (f, time.time() - t0)
        return returned
    return timer

def assert_match(value, expected):
    assert value == expected, "value %s != expected %s" % (
        value, expected)


#
# Test Case / Solution
#
@timeit    
def test_case():
    expected = 23
    triangle = """
    3
    7 4
    2 4 6
    8 5 9 3
"""

    graph = parse_triangle(triangle)
    assert_match(len(graph), 4)
    assert_match(len(graph[0]), 1)
    assert_match(len(graph[3]), 4)
    assert_match(graph[0][0], 3)
    assert_match(graph[2][1], 4)
    
    scored_graph = score_graph(graph)
    assert_match(len(scored_graph), 4)
    assert_match(len(scored_graph[0]), 1)
    assert_match(len(scored_graph[3]), 4)
    
    path = walk_scored_graph(scored_graph)
    values = nodes_to_values(path, graph)
    total = sum(values)
    
    assert_match(scored_graph[0][0], expected)    
    assert_match(total, expected)
    print "test case passed!"

@timeit
def solution():
    graph = parse_triangle(TRIANGLE)
    scored_graph = score_graph(graph)
    path = walk_scored_graph(scored_graph)
    values = nodes_to_values(path, graph)
    #print "path:", path
    
    summa = sum(values)
    assert_match(summa, scored_graph[0][0])
    return summa
        

#
# Support Code
#
def parse_triangle(source):
    """returns a dict of dicts where keys are row numbers (y) and values are
    dicts where key is col-num x and value is value"""
    graph = {}
    lines = source.strip().split("\n")
    
    for y in xrange(len(lines)):
        line = lines[y]
        cols = line.strip().split(" ")
        graph[y] = dict()
        
        for x in xrange(len(cols)):
            graph[y][x] = int(cols[x])
        
    return graph


def score_graph(graph):
    """returns a graph with nodes scored to facilitate pathfinding"""
    return sum_up_maxes(graph)

    
def sum_up_maxes(graph):
    """a graph scoring algorithm that starts at the bottom of the triangle
    tree and takes the max score of two child nodes and adds that to the parent
    rolling scores up the graph"""
    scored_graph = {}
    last_row = len(graph) - 1
    scored_graph[last_row] = dict(graph[last_row])
    
    y = last_row - 1
    
    while y >= 0:
        scored_graph[y] = dict()
        
        for x in graph[y]:
            scored_graph[y][x] = get_node_score(graph, scored_graph, y, x)
            
        y -= 1
            
    return scored_graph


def get_node_score(graph, scored_graph, y, x):
    """take the value of most valuable child node (from scored graph) of node
    at y,x and add that to node's score (from graph)"""
    self_score = graph[y][x]
    
    children = get_children(graph, y, x)
    scores = nodes_to_values(children, scored_graph)
    scored_children = zip(scores, children)
    max_child_score = sorted(scored_children)[-1][0]
    
    return max_child_score + self_score


def walk_scored_graph(scored_graph):
    route = [(0,0)]
    end_row = len(scored_graph) - 1
    y = 0
    
    while y < end_row:
        next_pt = choose_next_step(route, scored_graph)
        route.append(next_pt)
        y += 1
        
    return route


def choose_next_step(route, scored_graph):
    y, x = route[-1]
    
    children = get_children(scored_graph, y, x)
    child_scores = nodes_to_values(children, scored_graph)
    scored_children = zip(child_scores, children)
    
    max_child = sorted(scored_children)[-1]
    next_step = max_child[1]        
    return next_step


def get_children(grid, y, x):
    """returns a list of (y,x) tuples for all immediate children of node at
    y, x"""
    children = []
    below = y + 1
    left, right = x, x+1
    
    if below in grid and left in grid[below]:
        children.append((below, left))
        
    if below in grid and right in grid[below]:
        children.append((below, right))
        
    return children

    
def nodes_to_values(path, grid):
    """path is a list of tuples (y,x) in path"""
    values = []
    
    for y, x in path:
        values.append(grid[y][x])
        
    return values
    
    

#
# Additional Tests
#



#
# Main
#
if __name__ == '__main__':
    test_case()
    print solution()
    